import 'package:account_book/common/dao/history_dao.dart';
import 'package:account_book/pages/chart/index.dart';
import 'package:flustars_flutter3/flustars_flutter3.dart';
import 'package:get/get.dart';

class ChartController extends GetxController {
  final state = ChartState();

  @override
  void onReady() {
    super.onReady();
    _loadData();
  }

  void switchDate(DateTime dateTime) {
    state.currentDate = dateTime;
    _loadData();
  }

  void switchDateType(int dateType) {
    state.dateType = dateType;
    _loadData();
  }

  void switchType(int type) async {
    state.type = type;
    _loadData();
  }

  void _loadData() async {
    DateTime now = state.currentDate;
    List<double> dataList = [];
    List<Map<String,dynamic>> countCategoryList = [];
    if (state.dateType == 1) {
      // 按月
      DateTime startDate = DateTime(now.year, now.month, 1);
      DateTime endDate = DateTime(now.year, now.month + 1, 0, 23, 59, 59);
      final list = await HistoryDao.instance.queryGroupDayByDate(
          DateUtil.formatDate(startDate, format: "yyyy-MM-dd"),
          DateUtil.formatDate(endDate, format: "yyyy-MM-dd"),
          state.type);
      for (int i = 1; i <= endDate.day; i++) {
        Map<String, dynamic>? map =
            list.firstWhereOrNull((item) => int.parse(item['date']) == i);
        if (map != null) {
          dataList.add(map['total']);
        } else {
          dataList.add(0);
        }
      }
      // 按类别查询
      countCategoryList = await HistoryDao.instance.queryGroupCategoryByDate(DateUtil.formatDate(startDate, format: "yyyy-MM-dd"),
          DateUtil.formatDate(endDate, format: "yyyy-MM-dd"),
          state.type);
    } else if (state.dateType == 2) {
      DateTime startDate = DateTime(now.year, 1, 1);
      DateTime endDate = DateTime(now.year, 12, 31);
      final list = await HistoryDao.instance.queryGroupMonthByDate(
          DateUtil.formatDate(startDate, format: "yyyy-MM-dd"),
          DateUtil.formatDate(endDate, format: "yyyy-MM-dd"),
          state.type);
      for (int i = 1; i <= 12; i++) {
        Map<String, dynamic>? map =
            list.firstWhereOrNull((item) => int.parse(item['date']) == i);
        if (map != null) {
          dataList.add(map['total']);
        } else {
          dataList.add(0);
        }
      }
      // 按类别查询
      countCategoryList = await HistoryDao.instance.queryGroupCategoryByDate(DateUtil.formatDate(startDate, format: "yyyy-MM-dd"),
          DateUtil.formatDate(endDate, format: "yyyy-MM-dd"),
          state.type);
    }

    state.chartData.clear();
    state.chartData.addAll(dataList);

    state.totalNum = 0;
    state.totalAmount = 0.0;
    state.countCategory.clear();

    for(Map<String,dynamic> map in countCategoryList) {
      state.totalAmount = NumUtil.add(state.totalAmount, map['amount']);
      state.totalNum += map['total'];
    }

    state.countCategory.addAll(countCategoryList);
  }
}
